package com.ly.consumer.thread.threadSafety;


//解决线程安全的问题:
// 1.同步代码块  把代码放在同步代码块中 只允许一个线程进入同步代码块中，等执行完释放掉锁后再让下一个线程进来
class Ticket implements Runnable{
    //运行场景:多个售卖口卖票
    private int ticket = 100;
    //synchronized () 随便一个对象就行 锁必须同一个对象 多个对象不行
    //1.object 推荐用这个
    Object lock = new Object();
    //2.this 调用对象
    //3.本身class 对象
    @Override
    public void run() {
        while (true){
            synchronized (lock){
//            synchronized (this){
//            synchronized (Ticket.class){
                if(ticket>0){
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"卖了"+ticket--);
                }
            }
        }
    }
}
public class MySynchronizedBlock {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        Thread t1 = new Thread(ticket);
        t1.setName("t1窗口");
        Thread t2 = new Thread(ticket);
        t2.setName("t2窗口");
        Thread t3 = new Thread(ticket);
        t3.setName("t3窗口");
        t1.start();
        t2.start();
        t3.start();
    }
}
